package chatroom;

import common.ChatMessage;
import common.DataExchange;
import common.Utils;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;

import static common.Constants.*;

/**
 * @author LinLe
 * @create 2020-12-22 9:45
 */
public class ChatroomClient {
    //表示接收方
    private String currentToName;
    //表示当前用户
    private String userName;
    private DataExchange de;
    //ip地址
    private String server;
    private Scanner sn = new Scanner(System.in);
    
    public ChatroomClient( String server) throws IOException {
        System.out.println("客户端正在连接中........");
        this.server = server;
        Socket s = new Socket(server, SERVER_PORT);
        System.out.println("客户端已连接到服务器："+ s.getRemoteSocketAddress());
        de = new DataExchange(s);
    }
    public void start(){
        //初始化名字
        initName();
        //开启读服务器端来的消息的线程
        Thread readThread = new Thread(() -> {
            while(true){
                try {
                    ChatMessage chatMessage = de.receive();
                    //若是读到bye则关闭通信，程序结束
                    if(chatMessage.getFrom() == ADMIN_NAME &&
                    chatMessage.getMessage().trim().equalsIgnoreCase( "bye")){
                        de.close();
                        System.out.println(  "已离开聊天室,程序结束");
                        System.exit(0);
                    }
                    //输出服务器端的信息
                    System.out.println("from \"" + chatMessage.getFrom() + "\":" + chatMessage.getMessage());
                } catch (IOException e) {
                        e.printStackTrace();
                        de.close();
                        System.exit(-2);
                }
    
            }
        });
        readThread.start();
    
        //开启往服务器端写的消息的线程
        Thread writeThread = new Thread(() -> {
            while(true){
                try {
                    //发送信息
                    de.send(createChatMessage());
                } catch (Exception e) {
                    e.printStackTrace();
                    de.close();
                    System.exit(-3);
                }
            }
        });
        writeThread.start();
    }
    //创建信息
    private ChatMessage createChatMessage() {
        
        while(true){
            String message = null;
            String line = null;
            String to = null;
            try {
                line = sn.nextLine();
                //对信息的格式进行筛选
                if(line.startsWith(CHAT_WITH_START)){
                    to = line.substring(1, line.indexOf(SPACE_STRING)).trim();
                    String errorMsg = Utils.isValidToUserName(to);
                    if(errorMsg == null){
                        currentToName = to;
                        message = line.substring(line.indexOf(SPACE_STRING)+1).trim();
                    }else{
                        System.out.println("输入的用户名字"+to+"不合法");
                        continue;
                    }
                }else{
                    currentToName = null;
                    message = line;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("输入的消息不对：" + line);
                continue;
            }
            return new ChatMessage(userName,currentToName,message);
        }
        
    }
    
    private void initName() {
        String typeName = null;
        while(true){
            try {
                
                ChatMessage chatMsg = de.receive();
                String chatMsgMessage = chatMsg.getMessage();
                //从服务器端接受信息若是UserNamePass则用户注册成功
                if(chatMsgMessage.equalsIgnoreCase( USER_NAME_PASS)){
                    userName = chatMsg.getTo();
                    break;
                }else{
                    System.out.println(chatMsgMessage);
                    //否则重新注册
                    typeName = sn.nextLine();
                    de.send(new ChatMessage(NO_NAME,ADMIN_NAME,typeName.trim()));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }
}
